package com.mpj.yolov12;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Surface;
import android.view.View;
import android.widget.FrameLayout;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;

public class CustomActivity extends AppCompatActivity {
    private static final String TAG = "CustomActivity";
    public static final int REQUEST_CAMERA = 100;
    private final Yolov12 yolov12 = new Yolov12();
    private static final int current_model = 0;
    private static final int current_cpugpu = 0;
    private BitmapSurfaceView cameraView; // 已修正类型

    private final Handler handler = new Handler();

    private static int index = 1;
    private static boolean isScanning = false;

    private final Runnable imageLoadTask = new Runnable() {
        @Override
        public void run() {
            isScanning = true;
            try {
                Bitmap originalBitmap = AssetImageLoader.getBitmapFromAssets(CustomActivity.this, "test" + index + ".jpg", 640, 480);
//                Drawable drawable = ContextCompat.getDrawable(CustomActivity.this, R.drawable.test1);
//                Bitmap originalBitmap = ImageUtils.drawable2Bitmap(drawable);
                if (originalBitmap == null) {
                    LogUtils.e(TAG, "originalBitmap is null");
                    return;
                }
                LogUtils.d(TAG, "Original Bitmap: " + originalBitmap.getWidth() + "x" + originalBitmap.getHeight());

                // 缩放到 640x480
                Bitmap scaledBitmap = Bitmap.createScaledBitmap(
                        originalBitmap,
                        640, 480,
                        true
                );

                // 释放原始 Bitmap
                if (originalBitmap != scaledBitmap) {
                    originalBitmap.recycle();
                }

                LogUtils.d(TAG, "Scaled Bitmap: " + scaledBitmap.getWidth() + "x" + scaledBitmap.getHeight());

                Surface surface = cameraView.getHolder().getSurface();
                // 示例：将 Bitmap 转换为 RGBA 字节数组
                byte[] imageData = BitmapUtil.bitmapToRGBABytes(scaledBitmap); // 需实现该工具方法
                yolov12.processImage(imageData, surface);
                scaledBitmap.recycle();

                LogUtils.d(TAG, "imageLoadTask: " + scaledBitmap.getWidth() + "x" + scaledBitmap.getHeight());
            } catch (Exception e) {
                LogUtils.e(TAG, "imageLoadTask: " + e);
                isScanning = false;
                index = 1;
            } finally {
                if (index < 6) {
                    index++;
                    handler.postDelayed(this, 1000); // 重新安排下次执行
                } else {
                    isScanning = false;
                    index = 1;
                }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_custom);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        cameraView = findViewById(R.id.camera_view);
        cameraView.getHolder().setFormat(PixelFormat.RGBA_8888);
//        // 重置 FrameLayout.LayoutParams
//        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
//                640,  // 宽度
//                480    // 高度
//        );
//        cameraView.setLayoutParams(params);

        reload();
    }


    @Override
    public void onResume() {
        super.onResume();
        if (ContextCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CAMERA);
        }
        handler.post(imageLoadTask); // 启动定时任务
    }

    @Override
    protected void onPause() {
        super.onPause();
        handler.removeCallbacks(imageLoadTask); // 停止任务
    }

    private void reload() {
        boolean ret_init = yolov12.loadModel(getAssets(), current_model, current_cpugpu);
        if (!ret_init) {
            Log.e(TAG, "loadModel failed");
        }
    }

    public void onScanClick(View view) {
        if (!isScanning){
            handler.post(imageLoadTask);
        }
    }

}